package com.woniuxy.service.impl;

import com.woniuxy.client.CustomerFlowableClient;
import com.woniuxy.dto.CustomerApprovalDto;
import com.woniuxy.dto.CustomerProcessDto;
import com.woniuxy.entity.CustomerBasicInfo;
import com.woniuxy.service.CustomerApprovalService;
import com.woniuxy.service.CustomerApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户审批服务实现
 */
@Slf4j
@Service
public class CustomerApprovalServiceImpl implements CustomerApprovalService {

    @Autowired
    private CustomerFlowableClient flowableClient;

    @Autowired
    private CustomerApplicationService customerApplicationService;

    @Override
    public String startCustomerApprovalProcess(Long customerId, String currentUser) {
        try {
            CustomerBasicInfo customer = customerApplicationService.getCustomerApplicationById(customerId);
            if (customer == null) {
                throw new RuntimeException("客户不存在");
            }

            // 准备流程变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("customerId", String.valueOf(customer.getId()));
            variables.put("customerName", customer.getCustomerName());
            variables.put("applicant", currentUser);
            variables.put("callbackUrl", "http://localhost:8001/api/customers/callback");

            // 启动流程
            String processInstanceId = flowableClient.startProcess(
                "NewCustomer",
                String.valueOf(customer.getId()),
                variables
            );

            // 更新客户状态
            customer.setProcessInstanceId(processInstanceId);
            customer.setApprovalStatus("APPROVING");
            customerApplicationService.updateCustomerStatus(customerId, "APPROVING", "流程已启动");

            log.info("客户审批流程启动成功，客户ID：{}，流程实例ID：{}", customerId, processInstanceId);
            return processInstanceId;

        } catch (Exception e) {
            log.error("启动客户审批流程失败", e);
            throw new RuntimeException("启动审批流程失败: " + e.getMessage());
        }
    }

    @Override
    public void completeApprovalTask(CustomerApprovalDto approvalDto, String currentUser) {
        try {
            // 准备任务完成变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("approved", "APPROVED".equals(approvalDto.getApprovalResult()));
            variables.put("approvalComment", approvalDto.getApprovalComment());
            variables.put("approver", currentUser);

            // 完成任务
            flowableClient.completeTask(approvalDto.getTaskId(), variables);

            log.info("审批任务完成，任务ID：{}，审批结果：{}", 
                approvalDto.getTaskId(), approvalDto.getApprovalResult());

        } catch (Exception e) {
            log.error("完成审批任务失败", e);
            throw new RuntimeException("完成审批任务失败: " + e.getMessage());
        }
    }

    @Override
    public List<Map<String, Object>> getUserTasks(String userName) {
        try {
            flowableClient.getTasksByAssignee(userName);
            // 解析响应并返回任务列表
            // 这里需要根据实际的响应格式进行解析
            return null; // 临时返回null，需要实现解析逻辑
        } catch (Exception e) {
            log.error("查询用户待办任务失败", e);
            throw new RuntimeException("查询待办任务失败: " + e.getMessage());
        }
    }

    @Override
    public List<CustomerProcessDto.ProcessStepDto> getProcessSteps(String processInstanceId) {
        try {
            String response = flowableClient.getProcessSteps(processInstanceId);
            // 解析并转换为ProcessStepDto列表
            // 这里需要根据实际的响应格式进行解析
            log.info("查询流程步骤响应: {}", response);
            return null; // 临时返回null，需要实现解析逻辑
        } catch (Exception e) {
            log.error("查询流程步骤失败", e);
            throw new RuntimeException("查询流程步骤失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getProcessStatus(String processInstanceId) {
        try {
            flowableClient.getProcessStatus(processInstanceId);
            // 解析响应并返回状态信息
            // 这里需要根据实际的响应格式进行解析
            return null; // 临时返回null，需要实现解析逻辑
        } catch (Exception e) {
            log.error("查询流程状态失败", e);
            throw new RuntimeException("查询流程状态失败: " + e.getMessage());
        }
    }

    @Override
    public void handleProcessCallback(Map<String, Object> callbackData) {
        try {
            Long customerId = Long.valueOf(callbackData.get("customerId").toString());
            String status = callbackData.get("status").toString();
            String reason = callbackData.get("reason") != null ? 
                callbackData.get("reason").toString() : null;

            // 更新客户状态
            customerApplicationService.updateCustomerStatus(customerId, status, reason);

            log.info("处理流程回调成功，客户ID：{}，状态：{}", customerId, status);

        } catch (Exception e) {
            log.error("处理流程回调失败", e);
            throw new RuntimeException("处理流程回调失败: " + e.getMessage());
        }
    }
}
